/*
 * ActiveDirectory
 *
 * Creado el 18/02/2009, 07:32:18 PM
 */
package com.unicon.autoservicio.util;

import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.apache.log4j.Logger;

/**
 *
 * @author Ricardo Rodríguez
 */
public final class ActiveDirectory {
   private static Logger logger = Logger.getLogger(ActiveDirectory.class.getName());

   public static String validarUsuario(String usuario, String clave) {
      Hashtable<String,String> env = new Hashtable<String,String>();
      ResourceBundle bundle = ResourceBundle.getBundle("activeDirectory");
      env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      env.put(Context.PROVIDER_URL, bundle.getString("provider_url").trim());
      env.put(Context.SECURITY_AUTHENTICATION, bundle.getString("security.authentication").trim());
      StringBuffer principal = new StringBuffer(usuario);
      principal.append("@").append(bundle.getString("security.domain").trim());
      env.put(Context.SECURITY_PRINCIPAL, principal.toString());
      env.put(Context.SECURITY_CREDENTIALS, clave);
      bundle = null;

      String nombreUsuario = "";
      try {
         //Create the initial directory context
         LdapContext ctx = new InitialLdapContext(env, null);

         //Specify the attributes to return
         String returnedAtts[] = {"cn", "objectClass", "distinguishedName",
            "lastLogoff", "lastLogon", "accountExpires", "memberOf", "name"};
         Attributes answer = ctx.getAttributes("", returnedAtts);
         if (answer.size() > 0) {
            if (logger.isDebugEnabled()) {
               StringBuffer sb = new StringBuffer("Usuario ");
               sb.append(principal.toString()).append(" válido");
               logger.debug(sb.toString());
            }
            nombreUsuario = answer.get("distinguishedName").get().toString();
         }
         ctx.close();

      } catch (Exception e) {
         logger.warn(e.getMessage());
      }
      return nombreUsuario;
   }

   public static String validarUsuario(String usuario) {
      Hashtable<String, String> env = new Hashtable<String, String>();
      ResourceBundle bundle = ResourceBundle.getBundle("activeDirectory");
      env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      env.put(Context.PROVIDER_URL, bundle.getString("provider_url").trim());
      env.put(Context.SECURITY_AUTHENTICATION, bundle.getString("security.authentication").trim());
      env.put(Context.SECURITY_PRINCIPAL,bundle.getString("security_principal").trim());
      env.put(Context.SECURITY_CREDENTIALS,bundle.getString("security_credential".trim()));
      bundle = null;

      String nombreUsuario = "";


      try {
         //Create the initial directory context
         LdapContext ctx = new InitialLdapContext(env, null);

         String returnedAtts[] = {"cn", "objectClass", "distinguishedName",
            "lastLogoff", "lastLogon", "accountExpires", "memberOf", "name"};

         StringBuffer filter = new StringBuffer("sAMAccountName=");
         filter.append(usuario);

         SearchControls ctls = new SearchControls();
         ctls.setReturningAttributes(returnedAtts);
         ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

         // Search for objects that have those matching attributes
         NamingEnumeration<SearchResult> answer =
                 ctx.search("", filter.toString(),ctls);
         SearchResult sr = null;

         while (answer.hasMore()) {
            sr = answer.next();
            nombreUsuario = sr.getAttributes().get("distinguishedName").get().toString();
            if(logger.isDebugEnabled()){
               logger.debug(nombreUsuario);
            }
         }
         ctx.close();

      } catch (Exception e) {
         logger.debug(e.getMessage(), e);
      }

      return nombreUsuario;
   }
}
